<template>
  <div class="image-uploader">
    <el-upload
      class="upload-demo"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="customUpload"
    >
      <el-button type="primary">选择图片</el-button>
    </el-upload>
    <div v-if="previewUrl" class="preview">
      <img :src="previewUrl" alt="Preview" />
      <div class="image-info">
        <p>原始大小: {{ originalSize }}</p>
        <p>压缩后大小: {{ compressedSize }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import Compressor from 'compressorjs'

export default {
  name: 'ImageUploader',
  data() {
    return {
      previewUrl: '',
      originalSize: '',
      compressedSize: ''
    }
  },
  methods: {
    beforeUpload(file) {
      // 检查文件类型
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      return true
    },
    customUpload({ file }) {
      this.originalSize = this.formatFileSize(file.size)
      
      return new Promise((resolve, reject) => {
        new Compressor(file, {
          quality: 0.6, // 压缩质量，范围0-1
          maxWidth: 1920, // 最大宽度
          maxHeight: 1920, // 最大高度
          success: (compressedFile) => {
            this.compressedSize = this.formatFileSize(compressedFile.size)
            this.previewUrl = URL.createObjectURL(compressedFile)
            
            // 这里可以调用你的上传API
            // const formData = new FormData()
            // formData.append('file', compressedFile)
            // 发送到服务器的代码...
            
            resolve(compressedFile)
          },
          error(err) {
            this.$message.error('图片压缩失败')
            reject(err)
          }
        })
      })
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  }
}
</script>

<style scoped>
.image-uploader {
  padding: 20px;
}

.preview {
  margin-top: 20px;
}

.preview img {
  max-width: 300px;
  max-height: 300px;
  object-fit: contain;
}

.image-info {
  margin-top: 10px;
}

.image-info p {
  margin: 5px 0;
  color: #666;
}
</style> 